package com.fenghongzhang.module_user.login


import android.annotation.SuppressLint
import android.content.ContentResolver
import android.provider.ContactsContract
import android.util.Log
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.fenghongzhang.lib_base.core.BaseActivity
import com.fenghongzhang.lib_common.ARouterCons
import com.fenghongzhang.lib_common.utils.delegate
import com.fenghongzhang.lib_common.utils.toast
import com.fenghongzhang.module_user.databinding.UserActivityLoginBinding
import com.fenghongzhang.module_user.db.AppDatabase
import com.fenghongzhang.module_user.model.User
import com.fenghongzhang.module_user.provider.MyContentProvider
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

private const val TAG = "LoginActivity"
@AndroidEntryPoint
@Route(path = ARouterCons.LOGIN_ACTIVITY)
class LoginActivity : BaseActivity<UserActivityLoginBinding, LoginViewModel>(UserActivityLoginBinding::inflate) {


    override val viewModel: LoginViewModel by viewModels()

    @SuppressLint("Range")
    override fun initView() {

        //验证权限
        XXPermissions.with(this)
            // 申请单个权限
            .permission(Permission.READ_CONTACTS)
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        toast("获取部分权限成功，但部分权限未正常授予")
                        return
                    }
                    toast("获取录音和日历权限成功")
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        toast("被永久拒绝授权，请手动授予录音和日历权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@LoginActivity, permissions)
                    } else {
                        toast("获取录音和日历权限失败")
                    }
                }
            })

        binding.apply {
            etUsername.addTextChangedListener { username ->
                viewModel.sendEvent(LoginIntent.UsernameChanged(username.toString()))
            }
            etPassword.addTextChangedListener { password ->
                viewModel.sendEvent(LoginIntent.PasswordChanged(password.toString()))
            }
            // 1, 登录按钮点击事件
            btnLogin.setOnClickListener {
                //2, 发送登录
//                viewModel.sendEvent(LoginIntent.LoginClicked)
                ARouter.getInstance().build(ARouterCons.HOME_ACTIVITY).navigation()

            }
            //1一键登录
            btnQuickLogin.setOnClickListener{
//                //获取手机通信录
//                val contentResolver: ContentResolver = contentResolver
//                val cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null)
//                cursor?.use {
//                    while (it.moveToNext()) {
//                        val id = it.getString(it.getColumnIndex(ContactsContract.Contacts._ID))
//                        val name = it.getString(it.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
//                        Log.d(TAG, "Contact ID: $id, Name: $name")
//                    }
//                }
//                cursor?.close()

                //创建数据库
//                val db = Room.databaseBuilder(
//                    applicationContext,
//                    AppDatabase::class.java, "a2207"
//                )
////                    .allowMainThreadQueries()
//                    .build()
                lifecycleScope.launch {
                    val database = AppDatabase.getDatabase(applicationContext)
                    //database.userDao().insertAll(User(1, "1", "1"))
                }

                val contentResolver: ContentResolver = contentResolver
                val cursor = contentResolver.query(MyContentProvider.CONTENT_URI,null,null,null,null)
                cursor?.use {
                    while (it.moveToNext()) {
                        val id = it.getString(it.getColumnIndex("uid"))
                        val name = it.getString(it.getColumnIndex("first_name"))
                        Log.d(TAG, "Contact ID: $id, Name: $name")
                    }
                }
                cursor?.close()

            }
        }
    }

    override fun initData() {
        //22, 收集状态具体处理方法
        collectState(viewModel.state) { state ->
            updateUI(state)
        }
    }

    // 23,更新UI
    private fun updateUI(state: LoginState) {
        binding.apply {
            if (state.isLoading) {

            }
            if(state.isSucess){
                Log.i(TAG, "updateUI: ${state.userInfo}")
                Logger.d("updateUI: ${state.userInfo}");
                Logger.json(state.userInfo.toString());
                ARouter.getInstance().build(ARouterCons.HOME_ACTIVITY).navigation()

            }
        }
    }
}